package com.mfrs.demos;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.io.FileUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mfrs.ActionResult;
import com.mfrs.BmpData;
import com.mfrs.FaceData;
import com.mfrs.IFRSMobileService;
import com.mfrs.util.ImageHelper;
import com.mfrs.util.SimpleFileDialog;
import com.mfrs.util.SimpleFileDialog.SimpleFileDialogListener;

import hk.cic.demointegrationapp.BuildConfig;
import hk.cic.demointegrationapp.R;

@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class MainActivity extends Activity {
	private final String TAG = "FRSMobileDemo";

	private static final int IMAGE_REQUEST1 = 1888;
	private static final int IMAGE_REQUEST2 = 1889;
	
	public static final int MAX_WIDTH = 1920;
	public static final int MAX_HEIGHT = 1080;

	private Button btnFromFile1;
	private Button btnCamera1;
	private Button btnFromFile2;
	private Button btnCamera2;
	private Button btnMatch;
	
	private EditText etDstFolder;
	private EditText etResizeScale;
	private EditText etResizeWidth;
	private EditText etResizeHeight;
	private TextView tvResizeResult;
	private ImageView ivResizeImg;
	private TextView tvTime;
	
	private com.mfrs.FaceData faceData1;
	private com.mfrs.FaceData faceData2;

	private Uri uriImage1;
	private Uri uriImage2;
	
	private byte[] resizedBmpData;
	
	private IFRSMobileService frsMobileService;
	private boolean isSvcConnected = false;
	private boolean isInit = false;


	
	public IFRSMobileService getFrsMobileService() {
		return frsMobileService;
	}
	
	private boolean connectToFrsMobileService() {
		isInit = false;
		Intent serviceIntent = new Intent();
		serviceIntent.setClassName("com.mfrs", "com.mfrs.FRSMobileService");
		isSvcConnected = bindService(serviceIntent, mServiceConnection, 				
				Context.BIND_AUTO_CREATE);
		Log.i(TAG,	"connectToFrsMobileService: "+ String.valueOf(isSvcConnected));
				
		return isSvcConnected;
	}
	
	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {			
			frsMobileService = IFRSMobileService.Stub.asInterface(service);
			showAlertDialog(R.string.msg_mfrs_init_ok, R.string.app_name);
			isInit = true;
			try {
				copyAssets();
			} catch (Exception e) {
				Log.e(TAG, "Error encountered in copying assets files.");
			}
			
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.e(TAG, "Service Disconnected.");
		}

	};


	private void showAlertDialog(int message, int title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setMessage(message).setTitle(title);
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private void showAlertDialog(String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setMessage(message).setTitle(title);
		AlertDialog dialog = builder.create();
		dialog.show();

	}

	private void showAlertDialog(ActionResult ar) {
		String message = "";
		if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
			message = "CODE_FaceNotFound: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_FRSEngineError) {

			message = "CODE_FRSEngineError: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_ImageFormatNotSupport) {
			message = "CODE_ImageFormatNotSupport: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData1) {
			message = "CODE_InvalidFeatureData1: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData2) {
			message = "CODE_InvalidFeatureData2: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseExpired) {
			message = "CODE_LicenseExpired: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseNotValid) {
			message = "CODE_LicenseNotValid: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_UnknownError) {
			message = "CODE_UnknownError: " + ar.getRemark();
		}
		showAlertDialog(message, getResources().getString(R.string.title_err));
	}	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
		if (isSvcConnected){
			Log.i(TAG, "unbindservice");
			this.unbindService(mServiceConnection);
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_face_main);

		Log.i(TAG, "onCreate");

		if (!isSvcConnected){
			isSvcConnected = connectToFrsMobileService();
			Log.i(TAG,	"onCreate Connect to FRS Mobile Service: " +	String.valueOf(isSvcConnected));			
		}	

		btnFromFile1 = (Button) findViewById(R.id.btnFromFile1);
		btnCamera1 = (Button) findViewById(R.id.btnCamera1);
		btnFromFile2 = (Button) findViewById(R.id.btnFromFile2);
		btnCamera2 = (Button) findViewById(R.id.btnCamera2);
		btnMatch = (Button) findViewById(R.id.btnMatch);
		ivResizeImg = (ImageView)findViewById(R.id.imageViewResizeImgSrc);
		etResizeScale = (EditText)findViewById(R.id.editTextResizeScale);
		etResizeWidth = (EditText)findViewById(R.id.editTextResizeWidth);
		etResizeHeight = (EditText)findViewById(R.id.editTextResizeHeight);
		tvResizeResult = (TextView)findViewById(R.id.textViewResizeResult);
		tvTime = (TextView)findViewById(R.id.textViewTime);
		
		btnFromFile1.setOnClickListener(new OnClickListener() {
			String file1_chosen;
			@Override
			public void onClick(View v) {				
				if(!checkConn())
					return;
				
				if(BuildConfig.DEBUG){
					handleImage(IMAGE_REQUEST1, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/face/wang.jpg"));
					return;
				}
								
				try {
					
					SimpleFileDialog fileOpenDialog = new SimpleFileDialog(MainActivity.this, "FileOpen", new SimpleFileDialogListener(){
						
						@Override
						public void onChosenDir(String chosenDir){

							file1_chosen = chosenDir;
						
							Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " + file1_chosen, Toast.LENGTH_LONG).show();
							Log.i(TAG, String.format("File1 Chosen: %s", file1_chosen));
							
							File f = new File(file1_chosen);
							handleImage(IMAGE_REQUEST1, Uri.fromFile(f));

						}
					});
			
					fileOpenDialog.Default_File_Name = file1_chosen;
					fileOpenDialog.chooseFile_or_Dir();
				} catch (Exception e) {					
					showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
					e.printStackTrace();
				} 
				
			}

		});
		
		btnFromFile2.setOnClickListener(new OnClickListener() {	
			String file2_chosen;
			@Override
			public void onClick(View v) {
				if(!checkConn())
					return;
				
				if(BuildConfig.DEBUG){
					handleImage(IMAGE_REQUEST2, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/face/fan.png"));
					return;
				}

				try {
					
					SimpleFileDialog fileOpenDialog = new SimpleFileDialog(MainActivity.this, "FileOpen", new SimpleFileDialogListener() {
						
						@Override
						public void onChosenDir(String chosenDir) {
							file2_chosen = chosenDir;
							
							Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " + file2_chosen, Toast.LENGTH_LONG).show();
							Log.i(TAG, String.format("File2 Chosen: %s", file2_chosen));
							
							File f = new File(file2_chosen);
							handleImage(IMAGE_REQUEST2, Uri.fromFile(f));

						}
					});
					
					fileOpenDialog.Default_File_Name = file2_chosen;
					fileOpenDialog.chooseFile_or_Dir();
				} catch (Exception e) {					
					showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
					e.printStackTrace();
				} 
		

			}
		});

		btnCamera1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isSvcConnected) {
					if (!connectToFrsMobileService()) {						
						showAlertDialog(R.string.err_mfrs_not_found,
								R.string.title_err);
						return;
					}															
				}
				if (!isInit){
					showAlertDialog(R.string.err_mfrs_not_init,
							R.string.title_err);
					return;
				}

				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				String fileName = new SimpleDateFormat(
						"'image1_'yyyyMMddhhmm'.jpg'").format(new Date());
				uriImage1 = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory().getPath()
						+ "/"
						+ fileName));
				cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						uriImage1);
				startActivityForResult(cameraIntent, IMAGE_REQUEST1);

			}
		});
		btnCamera2.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!isSvcConnected) {
					if (!connectToFrsMobileService()) {						
						showAlertDialog(R.string.err_mfrs_not_found,
								R.string.title_err);
						return;
					}															
				}
				if (!isInit){
					showAlertDialog(R.string.err_mfrs_not_init,
							R.string.title_err);
					return;
				}

				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				String fileName = new SimpleDateFormat(
						"'image2_'yyyyMMddhhmm'.jpg'").format(new Date());
				uriImage2 = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory().getPath()
						+ "/"
						+ fileName));

				cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						uriImage2);
				startActivityForResult(cameraIntent, IMAGE_REQUEST2);

			}
		});

		btnMatch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isSvcConnected) {
					if (!connectToFrsMobileService()) {
						showAlertDialog(R.string.err_mfrs_not_found,
								R.string.title_err);
						return;
					}
				}
				
				if (!isInit){
					showAlertDialog(R.string.err_initialization_in_progress,
							R.string.title_err);
					return;
				}

				TextView tv = (TextView) findViewById(R.id.labelScoreResult);

				if (faceData1 != null && faceData2 != null) {

					Log.i(TAG, "try match");
					float[] score = new float[1];
					score[0] = -1.0f;

					try {
						long time = System.nanoTime();						
						ActionResult ar = frsMobileService.faceMatching(
								faceData1.getFeatureData(),
								faceData2.getFeatureData(), score);
						time = System.nanoTime() - time;
						//tvTime.setText("faceMatching used time: " + String.valueOf(time));
						
						if (ar.getCode() == ActionResult.CODE_Success) {
							Log.i(TAG, "score " + String.valueOf(score[0]));
							tv.setText(String.valueOf(score[0]));
							((TextView) findViewById(R.id.textViewError))
									.setText("");
						} else {
							showAlertDialog(ar);
							tv.setText("-");
							Log.e(TAG, "Err: " + String.valueOf(ar.getCode()));
							Log.e(TAG, "Err: " + ar.getRemark());
							((TextView) findViewById(R.id.textViewError))
									.setText(String.valueOf(ar.getCode()) + " "
											+ ar.getRemark());
						}

					} catch (RemoteException e) {

						Log.e(TAG, e.getMessage());
						showAlertDialog(R.string.err_mfrs_not_found,
								R.string.title_err);
						isSvcConnected = false;
						e.printStackTrace();
					}
				}else
				{
					tv.setText("-");
					Log.e(TAG, "Either FaceData1 or FaceData2 is null");
				}

			}
		});
				
		((Button)findViewById(R.id.btnResizeImgFromFile)).setOnClickListener(new OnClickListener(){
			String file3_chosen = "";
			@Override
			public void onClick(View v){
				if(!checkConn())
					return;
								
				try {
					
					SimpleFileDialog fileOpenDialog = new SimpleFileDialog(MainActivity.this, "FileOpen", new SimpleFileDialogListener(){
						
						@Override
						public void onChosenDir(String chosenDir){

							file3_chosen = chosenDir;
						
							Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " + file3_chosen, Toast.LENGTH_LONG).show();
							Log.i(TAG, String.format("File1 Chosen: %s", file3_chosen));
							
							File f = new File(file3_chosen);
							resizedBmpData = ImageHelper.getTransferrableBmpBytesFromFile(f);
							if(resizedBmpData != null){								
								setDisplayResizeImg(ImageHelper.loadBmpFromData(resizedBmpData));
							}
							else{								
								AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
		                        dialog.setTitle("Alert Dialog");
		                        dialog.setMessage("Invalid image file selected.");
		                        dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
					                public void onClick(DialogInterface dialog, int which) {
						                dialog.dismiss();
					                }
		                        });
		                        dialog.show();	
							}
						}
					});
						
					fileOpenDialog.Default_File_Name = file3_chosen;
					fileOpenDialog.chooseFile_or_Dir();
				} catch (Exception e) {					
					showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
					e.printStackTrace();
				} 
			}
		});
				
		((Button)findViewById(R.id.btnResizeImgScale)).setOnClickListener(new ResizeOnClickListener(this, ResizeType.SCALE));
		((Button)findViewById(R.id.btnResizeImgByDimension)).setOnClickListener(new ResizeOnClickListener(this, ResizeType.DIMENSION));
		
	}	
	
	private class Dimension{
		private final int width;
		private final int height;
		
		public Dimension(int width, int height)
		{
			this.width = width;
			this.height = height;
		}
		
		public int getWidth()
		{
			return this.width;
		}
		public int getHeight()
		{
			return this.height;
			
		}
	}
	
	
	public Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {		
	    int original_width = imgSize.width;
	    int original_height = imgSize.height;
	    int bound_width = boundary.width;
	    int bound_height = boundary.height;
	    int new_width = original_width;
	    int new_height = original_height;

	    // first check if we need to scale width
	    if (original_width > bound_width) {
	        //scale width to fit
	        new_width = bound_width;
	        //scale height to maintain aspect ratio
	        new_height = (new_width * original_height) / original_width;
	    }

	    // then check if we need to scale even with the new height
	    if (new_height > bound_height) {
	        //scale height to fit instead
	        new_height = bound_height;
	        //scale width to maintain aspect ratio
	        new_width = (new_height * original_width) / original_height;
	    }

	    return new Dimension(new_width, new_height);
	}
	
	
	@SuppressLint("DefaultLocale")
	private void handleImage(int imageRequest, Uri imageUri) {

		ImageView imgView = null;
		TextView isFaceFoundTextView = null;
		TextView faceQualityScoreTextView = null;
		TextView errTextView = (TextView) findViewById(R.id.textViewError);

		if (imageRequest == IMAGE_REQUEST1) {
			imgView = ((ImageView) findViewById(R.id.imageView1));
			isFaceFoundTextView = ((TextView) findViewById(R.id.textViewIsFaceFound1));
			faceQualityScoreTextView = ((TextView) findViewById(R.id.textViewFaceQualityScore1));
			faceData1 = null;
		} else if (imageRequest == IMAGE_REQUEST2) {
			imgView = ((ImageView) findViewById(R.id.imageView2));
			isFaceFoundTextView = ((TextView) findViewById(R.id.textViewIsFaceFound2));
			faceQualityScoreTextView = ((TextView) findViewById(R.id.textViewFaceQualityScore2));
			faceData2 = null;
		}

		Bitmap bMap, resizedBitmap, canvasBitmap = null;
		try {
			if (imageUri != null)
			{
				File f = new File(imageUri.getPath());
				if (f.exists()) {

					byte[] image = FileUtils.readFileToByteArray(f);
					int imageSize = image.length/1024;
					Log.i(TAG, String.format("Image size before resizing: %d", imageSize));
					
					bMap = BitmapFactory.decodeByteArray(image, 0, image.length);
					
					if (bMap != null)
					{
						Log.i(TAG, String.format("Current width * height: %d x %d ", bMap.getWidth(), bMap.getHeight() ));
						
						Dimension imgDimension = new Dimension(bMap.getWidth(), bMap.getHeight());
						Dimension boundaryHorizontalDimension = new Dimension(MAX_WIDTH, MAX_HEIGHT);
						Dimension boundaryVerticalDimension = new Dimension(MAX_HEIGHT, MAX_WIDTH);
						Log.i(TAG, String.format("Img Resolution before resizing: %d x %d", imgDimension.getWidth(), imgDimension.getHeight()));
			
						Dimension newDimension = imgDimension;
						Boolean resized = false;
						resizedBitmap = bMap;
						
						if (bMap.getWidth() > bMap.getHeight())
						{
							if (bMap.getWidth() > MAX_WIDTH || bMap.getHeight() > MAX_HEIGHT)
							{
								Log.i(TAG, String.format("Img Boundary: %d x %d", boundaryHorizontalDimension.getWidth(), boundaryHorizontalDimension.getHeight()));
								newDimension = getScaledDimension(newDimension, boundaryHorizontalDimension);
							    resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(), false);
							    resized = true;
							}
						}
						else
						{
							Log.i(TAG, "width < height");
							if (bMap.getWidth() > MAX_HEIGHT || bMap.getHeight() > MAX_WIDTH)
							{
								Log.i(TAG, String.format("Img Boundary: %d x %d", boundaryVerticalDimension.getWidth(), boundaryVerticalDimension.getHeight()));
								newDimension = getScaledDimension(newDimension, boundaryVerticalDimension);
								resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(), false);
								resized = true;
							}
						}
						
						Log.i(TAG, String.format("Img Resolution after resizing: %d x %d", resizedBitmap.getWidth(), resizedBitmap.getHeight()));

						ArrayList<FaceData> fdList = new ArrayList<FaceData>();
						ActionResult ar = null;
						
						if (resized)
						{
							ByteArrayOutputStream stream = new ByteArrayOutputStream();
							resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
							byte[] resizedImageByte = stream.toByteArray();
							int size = resizedImageByte.length / 1024;
							Log.i(TAG, "Size after resizing: " + resizedImageByte.length / 1024 + "KB");
	

							if ( size < 800 )
							{
								imgView.setImageBitmap(resizedBitmap);
								long time = System.nanoTime();
								ar = frsMobileService.faceDataDetection(resizedImageByte, fdList);
								time = System.nanoTime() - time;
								//tvTime.setText("faceDataDetection used time: " + String.valueOf(time));
							}
							else {
								showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
								Log.e(TAG, "Please keep image less than 800KB after compression");
							}
							
							resizedImageByte = null;
						}
						else {
							try {
								if (image.length / 1024 < 1000)
								{
									imgView.setImageBitmap(resizedBitmap);
									Log.i(TAG, "Before faceDataDetection");
									long time = System.nanoTime();
									ar = frsMobileService.faceDataDetection(image, fdList);
									time = System.nanoTime() - time;
									//tvTime.setText("faceDataDetection used time: " + String.valueOf(time));
									Log.i(TAG, "After faceDataDetection");
								}
								else
								{
									showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
									Log.e(TAG, "Image Size exceeds 1MB after compression");
								}

							} catch (Exception e) {
								Log.e(TAG, "Error in FaceDataDetection");
							}

						}
	
						if (ar != null)
						{
							if (ar.getCode() == ActionResult.CODE_Success) {
								if (fdList.size() > 0)
								{
									// highlight the head and eyes positions
									Log.i(TAG, String.format("Feature Data List Size: %d", fdList.size()));
									
									Bitmap copiedImage = resizedBitmap.copy(Bitmap.Config.ARGB_8888, true);
									Canvas canvas = new Canvas(copiedImage);

									try{
									    canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(), 
								    			Bitmap.Config.ARGB_8888);
									}
									catch (OutOfMemoryError e){
										while (canvasBitmap == null){
											System.gc();
											System.runFinalization();
											Log.i(TAG, "Draw On Image: Create Bitmap out Of Memory Error.\nCreate again now.");
											canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(), 
									    			Bitmap.Config.ARGB_8888);
										}
									}

									for (int i = 0; i < fdList.size(); i++)
									{
										int[] headArray = fdList.get(i).getHead();
										int[] leftEyeArray = fdList.get(i).getLeftEye();
										int[] rightEyeArray = fdList.get(i).getRightEye();
										
										if (headArray != null && leftEyeArray != null && rightEyeArray != null)
										{
											try {
												String rectString = String.format("New head in Main: left %d, top %d, right %d, bottom %d", headArray[0], headArray[1], 
														headArray[2], headArray[3]);
												Log.i(TAG, rectString);
								
												Paint rectpaint = new Paint();
												rectpaint.setStyle(Paint.Style.STROKE);
												rectpaint.setColor(Color.GREEN);
												rectpaint.setStrokeWidth(7);
												float leftx = headArray[0];
												float topy = headArray[1];
												float rightx = headArray[2];
												float bottomy = headArray[3];
												
												Paint cirpaint = new Paint();
												cirpaint.setStyle(Paint.Style.STROKE);
												cirpaint.setColor(Color.GREEN);
												cirpaint.setStrokeWidth(5);
												
												if (i == 0)
												{
													rectpaint.setColor(Color.CYAN);

													cirpaint.setColor(Color.CYAN);
												}											
												
												canvas.drawRect(leftx, topy, rightx, bottomy, rectpaint);
												canvas.drawCircle(leftEyeArray[0], leftEyeArray[1], 10, cirpaint);
												canvas.drawCircle(rightEyeArray[0], rightEyeArray[1], 10, cirpaint);
	
											} catch (Exception e) {
												Log.e(TAG, "Exception encountered in drawing Image");
												showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
												imgView.setImageBitmap(resizedBitmap);
											}

										}
										else {
											Log.e(TAG, "HeadArray or EyeArray is null");
											showAlertDialog(R.string.error_headeye_notok, R.string.title_err);
											imgView.setImageBitmap(resizedBitmap);
										}
									}
									
									imgView.setImageBitmap(copiedImage);
									
								}
								else
								{
									Log.e(TAG, "Cannot find feature data");
								}
								
								if (fdList.size() > 0) {
									isFaceFoundTextView.setText("Face Found: Yes");
									faceQualityScoreTextView.setText("Face Quality:" + String.valueOf(fdList
											.get(0).getFaceQualityScore()));

									if (imageRequest == IMAGE_REQUEST1) {
										faceData1 = fdList.get(0);

										Log.i(TAG, "set faceData1");
									} else if (imageRequest == IMAGE_REQUEST2) {
										faceData2 = fdList.get(0);
										Log.i(TAG, "set faceData2");
									}
									errTextView.setText("");
								}
							} else {
								showAlertDialog(ar);

								if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
									isFaceFoundTextView.setText("Face Found: No");
									faceQualityScoreTextView.setText("Face Quality: -");
									errTextView.setText("Face Not Found");
								} else {
									isFaceFoundTextView.setText("Face Found: Err");
									faceQualityScoreTextView.setText("Face Quality: Err");
									errTextView.setText(String.valueOf(ar.getCode()) + ": "
											+ ar.getRemark());
								}
							}
						}
						else
						{
							showAlertDialog(R.string.err, R.string.title_err);
							Log.e(TAG, "Action Result is null");
						}

					}
					else
					{
						showAlertDialog(R.string.err_imagefile, R.string.title_err);
						Log.e(TAG, "File does not exist!" + f.toString());
					}

				} else {
					showAlertDialog("File does not exist! " + f.toString(),
							getResources().getString(R.string.title_err));
					Log.e(TAG, "File does not exist!" + f.toString());
				}
			}
			else
			{
				showAlertDialog(R.string.err, R.string.title_err);
				Log.e(TAG, "ImageUri is null.");
			}	
			
			
			resizedBitmap = null;
			bMap = null;
			canvasBitmap = null;
			
			
		} catch (IOException e) {
			showAlertDialog(e.getMessage(),
					getResources().getString(R.string.title_err));
			e.printStackTrace();
		} catch (RemoteException e) {
			showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
			isSvcConnected = false;
			e.printStackTrace();
		} catch (Exception e){
			showAlertDialog(e.getMessage(), "ERROR");
			e.printStackTrace();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {			
				if (requestCode == IMAGE_REQUEST1) {
					handleImage(IMAGE_REQUEST1, uriImage1);	
				} else if (requestCode == IMAGE_REQUEST2) {
					handleImage(IMAGE_REQUEST2, uriImage2);
				}				
		}
		else {
			Log.e(TAG, "CameraIntent result code not ok.");
			return;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent settingsScreen = new Intent(getApplicationContext(),
					SettingsActivity.class);

			startActivity(settingsScreen);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void copyAssets()
	{
		AssetManager assetManager = getAssets();
		String[] files = null;
		try {

			files = assetManager.list("");
			
			for (String filename: files){
				Log.i(TAG, filename);
			}
			
			
	
		} catch (IOException e) {
			Log.e(TAG, "Failed to get asset file list.", e);
		}
		
		for (String filename : files){
			InputStream in = null;
			OutputStream out = null;
			
			try{
				if (!filename.startsWith("images") && !filename.startsWith("sounds") && 
						!filename.startsWith("webkit") && !filename.startsWith("webkitsec"))
				{
					in = assetManager.open(filename);
					File outFile = new File(getFilesDir().getAbsoluteFile(), filename);
					out = new FileOutputStream(outFile);
		
					copyFile(in, out);
				}		
			}catch(IOException e){
				Log.e(TAG, "Failed to copy asset file: " + filename, e);
			}finally{
				if (in != null){
					try{
						in.close();
					}catch (IOException e){
						Log.e(TAG, e.getMessage().toString());
					}
				}
				if (out != null){
					try{
						out.close();
					}catch (IOException e){
						Log.e(TAG, e.getMessage().toString());
					}					
				}					
			}
		}
	}
	
	private void copyFile(InputStream in, OutputStream out) throws IOException {
	    byte[] buffer = new byte[1024];
	    int read;
	    while((read = in.read(buffer)) != -1){
	      out.write(buffer, 0, read);
	    }
	}	

	private boolean checkConn(){
		if (!isSvcConnected) {
			if (!connectToFrsMobileService()) {						
				showAlertDialog(R.string.err_mfrs_not_found,
						R.string.title_err);
				return false;
			}															
		}
		if (!isInit){
			showAlertDialog(R.string.err_mfrs_not_init,
					R.string.title_err);
			return false;
		}
		return true;
	}
		
	public enum ResizeType{
		SCALE,
		DIMENSION
	}
			
	public void onResizeBmp(ResizeType type){				
		if(resizedBmpData!=null){
			Float scale = 0.0F;
			int width, height;
			width = height = 0;
			if(type == ResizeType.SCALE){				
				try{
					scale = Float.parseFloat(etResizeScale.getText().toString());
				}catch(NumberFormatException ex){
					tvResizeResult.setText("Invalid scale input");
					return;
				}			
			}else{
				try{
					width = Integer.parseInt(etResizeWidth.getText().toString());
					height = Integer.parseInt(etResizeHeight.getText().toString());
					if( width <= 0 || height <=0 ){
						tvResizeResult.setText("Dimension input cannot be smaller than 0");
						return;
					}
				}catch(NumberFormatException ex){
					tvResizeResult.setText("Invalid dimension input");
					return;
				}	
			}					
			
			BmpData bData = null;
			try{
				ActionResult ar = null;
				bData = new BmpData();
				long time = System.nanoTime();
						
				if(type == ResizeType.SCALE)	
					ar = frsMobileService.resizeByScale(resizedBmpData, scale, bData);
				else
					ar = frsMobileService.resizeByDimension(resizedBmpData, width, height, bData);				
				time = System.nanoTime() - time;
				//tvTime.setText( ((type == ResizeType.SCALE) ? "resizeByScale" : "resizeByDimension") + " used time: " + String.valueOf(time));
				
				if (ar.getCode() == ActionResult.CODE_Success) {
					Log.i(TAG, "Resize image completed.");
					tvResizeResult.setText("Resize image completed.");
				} else {
					showAlertDialog(ar);
					Log.e(TAG, "Err: " + String.valueOf(ar.getCode()));
					Log.e(TAG, "Err: " + ar.getRemark());
					tvResizeResult.setText(String.valueOf(ar.getCode()) + " "
										 + ar.getRemark());
				}
			} catch (RemoteException e) {
				Log.e(TAG, e.toString());
				showAlertDialog(R.string.err_mfrs_not_found,R.string.title_err);
				isSvcConnected = false;
				e.printStackTrace();
				return;
			}	
			
			Bitmap resizedBmp = null;			
			if(bData.getLength() > 0)
				 resizedBmp = BitmapFactory.decodeByteArray(bData.getData(), 0, bData.getLength());
			else{
				Log.e(TAG, "Resize returned 0 size byte array.");
				showAlertDialog("Failed to decode resized byte array into bitmap.", "Error");
				return;
			}		

			resizedBmpData = bData.getData();
			setDisplayResizeImg(resizedBmp);
			
			saveResizedImgFile(getNewResizedFilename(), Bitmap.CompressFormat.JPEG);

			Log.i(TAG, "Resized image update completed.");
		}
	}
	
	
	private class ResizeOnClickListener implements OnClickListener {
		MainActivity act;
		ResizeType type;
	    public ResizeOnClickListener(MainActivity act, ResizeType t) { 
	    	this.act=act;	
	    	this.type=t;
	    }
	    @Override
	    public void onClick(View v){
            act.onResizeBmp(type);
        } 
	}
	
	public void setResizeDstPath(String path){
		etDstFolder.setText(path);
	}
	
	private void setDisplayResizeImg(Bitmap bmp){
		ivResizeImg.setImageBitmap(bmp);	
		tvResizeResult.setText("Resize image dimension: " + bmp.getWidth() + "x" + bmp.getHeight() + " size: " + resizedBmpData.length);
	}	
	
	private void saveResizedImgFile(String filename, Bitmap.CompressFormat format){
		String dstDir = getFilesDir().getAbsoluteFile().getPath();		
		final String imgPath = dstDir + File.separator + filename;		
		FileOutputStream fos = null;
		try{
			fos = new FileOutputStream(imgPath); 
		    fos.write(resizedBmpData);
		    fos.close();
		}catch(Exception e){
			Log.e(TAG, e.toString());
		}		
		
		Log.i(TAG, "Output resized image : " + imgPath);

		showAlertDialog("Resized image file saved to " + imgPath, this.getResources().getString(R.string.app_name));
	}
	
	private String getNewResizedFilename(){
		File dir = getFilesDir().getAbsoluteFile();
		int count = 0;
		for(File f : dir.listFiles()){
			if(f.getName().toLowerCase().contains("resized"))
				count++;
		}
		count++;
		return "Resized" + String.valueOf(count) + ".jpg";
	}
	
}
